<?php

namespace App\Http\Utils\Currency;

use App\Exceptions\Exceptions\ValidationException;
use Payment\Client\Charge;
use Payment\Client\Notify;
use Payment\Config;
use Payment\Notify\PayNotifyInterface;

/**
 * Class AliPay
 * @package App\Http\Utils\Currency
 */
class AliPay extends ThirdPay
{
    /**
     * @return array
     */
    public function config()
    {
        return [
            'use_sandbox'     => false,
            'app_id'          => env('ALIPAY_APPID'),
            'sign_type'       => 'RSA2',
            'ali_public_key'  => realpath('../config/Key/alipay.txt'),
            'rsa_private_key' => realpath('../config/Key/alipay_private.txt'),
            'limit_pay'       => [
                'credit_group',
            ],
            'notify_url'      => env('ALIPAY_NOTIFY'),
            'return_url'      => isset($this->order->other['return_url']) ? $this->order->other['return_url'] : env('APP_URL'),
            'return_raw'      => false,
        ];
    }

    /**
     * @return array
     */
    public function payData()
    {
        return [
            'body'            => $this->order->body(),
            'subject'         => $this->order->title(),
            'order_no'        => $this->order->orderNum,
            'timeout_express' => $this->order->timeout(),
            'amount'          => $this->order->amount / 100,
            'return_param'    => 'test',
            'client_ip'       => $this->order->ip(),
            'goods_type'      => '1',
            'store_id'        => sprintf('StoreId_%s', $this->order->shopId),
            'quit_url'        => isset($this->order->other['quit_url']) ? $this->order->other['quit_url'] : env('APP_URL'),
        ];
    }

    /**
     * @return mixed
     * @throws ValidationException
     */
    public function pay()
    {
        if (isset($this->order->other['return_url']) && isset($this->order->other['quit_url'])) {
            return Charge::run(Config::ALI_CHANNEL_WAP, $this->config(), $this->payData());
        } else {
            throw new ValidationException([
                "支付宝支付参数other必须包含return_url(支付成功跳转地址)和quit_url(打断支付跳转地址)，可选参数(body，title)"
            ]);
        }
    }

    /**
     * @param PayNotifyInterface $notify
     * @return array
     */
    public function notify(PayNotifyInterface $notify)
    {
        return Notify::run(Config::ALI_CHARGE, $this->config(), $notify);
    }

}